package com.jt.resource.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.jt.system.service.ConsumerServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author 金帮嘉诚 @date 2021-08-20 星期五 14:51
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired//day05 sentinel 链路限流
    private ConsumerServiceImpl consumerService;


    @GetMapping("/echo02")//day05
    public String echo02() {
        return consumerService.doGetResource() + "02";
    }

    @GetMapping("/echo01")//day05
    public String echo01() {
        return consumerService.doGetResource();
    }


    @Autowired
    private RestTemplate loadBalancerRestTemplate;

    //降级
    private AtomicLong atomicLong = new AtomicLong(1);

    @GetMapping("/echo03")
    public String echo03() throws InterruptedException {
        long num = atomicLong.getAndIncrement();//该方法相当于线程安全的后缀++
        if (num % 2 == 0) {
            Thread.sleep(200);
        }
        return loadBalancerRestTemplate.getForObject("http://sca-provider/provider/echo/111", String.class);
    }


    /**
     * 热点限流 day07 针对参数限流
     * url:http://localhost:8090/consumer/findById?id=1
     */
    @GetMapping("/findById")
    @SentinelResource("res")
    public String doFindById(@RequestParam Integer id) {//加注解默认必须传值
        return "select by " + id;
    }

    /**
     * 测试权限限流
     * url:localhost:8090/consumer/authority?origin=app1
     * */
    @GetMapping("/authority")
    public String authority(String origin){
        return loadBalancerRestTemplate.getForObject("http://sca-provider/provider/echo/"+origin, String.class);
    }



    /**
     * 测试重定向
     * 跳转到 http://localhost:8090/html/index.html
     * */
    @GetMapping("/")
    public void index(HttpServletResponse response) throws IOException {
        //以下几句都是错误案例
//        return "redirect:/html/index.html";
//        return "/html/index.html";
//        return "forword:/html/index.html";
//        return "html/index";
//        return "forword:/html/index";
//        return "redirect:http://localhost:8090/html/index.html";
        response.sendRedirect("http://localhost:8090/html/index.html");
    }

}
